package top.went.service;

import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.went.db.dao.DemandDao;
import top.went.db.dao.SaleOppDao;
import top.went.db.mapper.DemandMapper;
import top.went.exception.NotFoundException;
import top.went.exception.ServiceException;
import top.went.pojo.DemandEntity;
import top.went.pojo.SaleOppEntity;
import top.went.pojo.SolutionEntity;
import top.went.utils.TrackLog;
import top.went.vo.DemandVo;
import top.went.vo.PageEntity;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 详细需求
 */
@Service
@Transactional(value = "transactionManager", rollbackFor = Exception.class)
public class DemandService {
    @Autowired
    private DemandDao demandDao;
    @Autowired
    private DemandMapper demandMapper;
    @Autowired
    private SaleOppService saleOppService;

    private static final Map<String,String> map = new HashMap<>();

    static {
        map.put("importance","importance");
        map.put("tbSaleOppByOppId.tbCustomerByCusId.cusName","cus_name");
        map.put("tbSaleOppByOppId.oppTheme","opp_theme");
    }

    /**
     * 新增需求
     * @param demandEntity
     * @return
     * @throws ServiceException
     */
    public boolean addDemand(DemandEntity demandEntity) throws ServiceException {
        System.out.println("详细需求："+demandEntity);
        try {
            if(demandEntity.getTbSaleOppByOppId() == null || demandEntity.getTbSaleOppByOppId().getOppId() == null){
                demandEntity.setTbSaleOppByOppId(null);
            } else {
                Long oppId = demandEntity.getTbSaleOppByOppId().getOppId();
//                System.out.println("oppID："+oppId);
                SaleOppEntity saleOppEntity = saleOppService.load(oppId);
//                System.out.println("机会："+saleOppEntity);
                String trackLog = TrackLog.getTrack(saleOppEntity,"需求分析");
//                System.out.println("记录跟踪日志！"+trackLog);
                saleOppEntity.setStage("需求分析");
                saleOppEntity.setStageStartTime(new java.sql.Date(new Date().getTime()));
                saleOppEntity.setTrackLog(trackLog);
                saleOppService.modifySaleOpp(saleOppEntity);
            }
            return demandDao.save(demandEntity) != null;
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("新增需求失败");
        }
    }

    /**
     * 修改需求
     * @param demandEntity
     * @return
     * @throws NotFoundException
     * @throws ServiceException
     */
    public boolean modifyDemand(DemandEntity demandEntity) throws NotFoundException, ServiceException {
        DemandEntity demandEntity1 = load(demandEntity.getDemandId());
        if (demandEntity1 == null)
            throw new NotFoundException("需求不存在");
        demandEntity1.setDemandTheme(demandEntity.getDemandTheme());
        demandEntity1.setRecordTime(demandEntity.getRecordTime());
        demandEntity1.setImportance(demandEntity.getImportance());
        demandEntity1.setDemandContent(demandEntity.getDemandContent());
        if(demandEntity.getTbSaleOppByOppId() != null && demandEntity.getTbSaleOppByOppId().getOppId() != null){
            demandEntity1.setTbSaleOppByOppId(demandEntity.getTbSaleOppByOppId());
        } else {
            demandEntity1.setTbSaleOppByOppId(null);
        }
        try {
            demandDao.save(demandEntity1);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("修改需求失败");
        }
    }

    /**
     * 删除需求
     * @param id
     * @return
     * @throws NotFoundException
     * @throws ServiceException
     */
    public boolean deleteDemand(Long id) throws NotFoundException, ServiceException {
        DemandEntity demandEntity = load(id);
        if (demandEntity == null)
            throw new NotFoundException("需求不存在");
        demandEntity.setIsDelete(1L);
        try {
            demandDao.save(demandEntity);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("删除需求失败");
        }
    }

    /**
     * 编辑删除
     * @param ids
     * @return
     * @throws NotFoundException
     * @throws ServiceException
     */
    public boolean deleteSelected(Long[] ids) throws NotFoundException, ServiceException {
        for(int i=0; i<ids.length; i++){
            deleteDemand(ids[i].longValue());
        }
        return true;
    }

    /**
     * 加载需求
     * @param id
     * @return
     */
    public DemandEntity load(Long id) throws NotFoundException {
        DemandEntity demandEntity = demandDao.findByDemandIdAndIsDelete(id, 0L);
        if(demandEntity == null){
            throw new NotFoundException("需求不存在！");
        }
        return demandEntity;
    }

    /**
     * 加载所有需求
     * @return
     */
    public List<DemandEntity> loadList(){
        return demandDao.findAllByIsDelete(0L);
    }

    /**
     * 分页加载所有需求
     * @param pageNumber
     * @param pageSize
     * @return
     */
    public List<DemandEntity> loadListByPage (Integer pageNumber, Integer pageSize) {
        PageRequest pageRequest = new PageRequest(pageNumber - 1, pageSize);
        return demandDao.findAllByIsDeleteOrderByDemandId(0L, pageRequest);
    }


    /**
     * 分页快速查询需求（重要程度、需求主题）
     * @param pageNumber
     * @param pageSize
     * @param demandEntity
     * @return
     */
    public Page<DemandEntity> loadListByPageAndParams (Integer pageNumber, Integer pageSize , DemandEntity demandEntity) {
        PageRequest pageRequest = new PageRequest(pageNumber - 1 , pageSize);
        String importance = demandEntity.getImportance() == null ? "": demandEntity.getImportance()+"" ;
        String demandTheme = demandEntity.getDemandTheme() == null? "" : demandEntity.getDemandTheme();
        return demandDao.findAllByIsDeleteWhere(0L, "%"+importance+"%", "%"+demandTheme+"%" ,  pageRequest);
    }

    /**
     * 高级查询
     * @param demandVo
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Transactional(rollbackFor = Exception.class, transactionManager = "transactionManager-my")
    public PageEntity<DemandEntity> findAllSeniorSearch(DemandVo demandVo, Integer pageNum, Integer pageSize) {
        String order = demandVo.getPage().getSort(map);
        if(order.length() <= 0){
            order = "demand_id desc";
        }
        com.github.pagehelper.Page<DemandEntity> page = PageHelper.startPage(pageNum,pageSize,order+" nulls last");
        demandMapper.findAllSeniorSearch(demandVo);
        return new PageEntity<>(page.getTotal(), page.getResult());
    }

}
